package apps.softtech.fastmarket;


import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import apps.softtech.Utility.ConnectionDetector;
import apps.softtech.Utility.RequestDataFromServer;
import apps.softtech.fastmarket.adapter.AdapterSearchUser;
import apps.softtech.fastmarket.model.DatabaseHandler;
import apps.softtech.fastmarket.model.Product;
import apps.softtech.fastmarket.model.UserInfo;

public class ActivitySearchUser extends Activity{
	ArrayList<UserInfo> mUserInfoList = new ArrayList<UserInfo>();
	AdapterSearchUser mAdapterSearchUser;
	ListView lvSearchUser;
	Context mContext;
	/**
	 * auto remember search
	 */
	String[] mRememberSearch={""};
	ArrayAdapter<String> mArrayAdapter;
	/**
	 * name to search
	 */
	AutoCompleteTextView actvUserName;
	Button btSearchUserName;
	/**
	 * user name search
	 */
	String content;
	String mUserName;
	/**
	 * database
	 */
	DatabaseHandler dbh;
	
	DisplayImageOptions options;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_user);
		//
		//init imageloader/
		//
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ActivitySearchUser.this).build();
    	ImageLoader.getInstance().init(config);
    	//register gcm
		new RegisterGoogleCM(ActivitySearchUser.this).registerGCM();
		//display imageloader
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.ic_launcher)
		.showImageForEmptyUri(R.drawable.ic_launcher)
		.showImageOnFail(R.drawable.ic_launcher)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(20))
		.build();
		
		
		init();
		initFuntion();
	}
	/**
	 * init
	 */
	private void init() {
		mContext = ActivitySearchUser.this;
		dbh = new DatabaseHandler(mContext);
		lvSearchUser = (ListView)findViewById(R.id.lvSearchUser);
		actvUserName = (AutoCompleteTextView)findViewById(R.id.actvUserName);
		btSearchUserName = (Button)findViewById(R.id.btSearchInfoUser);
//		new AsyncTaskGetUserInfo().execute();//
		mArrayAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1,mRememberSearch);
		actvUserName.setAdapter(mArrayAdapter);
		actvUserName.setThreshold(2);
		
	}
	/**
	 * init function
	 */
	private void initFuntion() {
		actvUserName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(actvUserName.getText().toString().equals("")||actvUserName.getText().toString().equals(null)){
					mUserInfoList.clear();
					setData();
				}
			}
		});
		actvUserName.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int position,
					long arg3) {
				content =(String) parent.getItemAtPosition(position);;
				if(content.equals("")||content.equals(null)){
					mUserInfoList.clear();
					setData();
				}else{
					new AsyncTaskGetUserInfo().execute();
				}
				
			}
		});
		btSearchUserName.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				content = actvUserName.getText().toString().trim();
				mUserInfoList.clear();
				setData();
				if(content.equals("")||content.equals(null)){
					
				}else{
					mUserInfoList.clear();
					ConnectionDetector cd = new ConnectionDetector(mContext);
					if(cd.isConnectingToInternet()){
						dbh.deleteUserInfo(UserInfo.USERID + " >=0", null);
					new AsyncTaskGetUserInfo().execute();
					}else{
						//cho` xay dung lai database client
//						mUserInfoList = dbh.getUserInfo(null, null, null, null, null);
					}
				}
			}
		});
	}
	/**
	 * set data adapter
	 */
	private void setData(){
		mAdapterSearchUser = new AdapterSearchUser(mUserInfoList, mContext,options);
		lvSearchUser.setAdapter(mAdapterSearchUser);
	}
	class AsyncTaskGetUserInfo extends AsyncTask<Void, Void, Void>{
		ProgressDialog dp;
		@Override
		protected void onPreExecute() {
			dp = new ProgressDialog(mContext);
			dp.setMessage("Searching......");
			dp.show();
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			try{
			JSONArray jsonData = new JSONArray();
			JSONObject jsonCategoryParentList = new JSONObject(new RequestDataFromServer().requestUserInfo(content));
			int success = jsonCategoryParentList.getInt("success");
			if(success==1){
				jsonData = jsonCategoryParentList.getJSONArray("data");
				Log.v("", jsonData.toString());
				for(int i=0;i<jsonData.length();i++){
					JSONObject jsonList = new JSONObject(jsonData.getJSONObject(i).toString());
					
					dbh.insertUserInfo(new UserInfo(jsonList.getString("st_UserName"), 
							jsonList.getString("st_Email"), jsonList.getString("st_PhoneNumber"),
							jsonList.getInt("st_Rate"), jsonList.getString("st_AvatarPath"),jsonList.getInt("st_UserId")));
				
				}
			}
			}catch(Exception e){}
			Log.v("", "sdfgh");
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			mUserInfoList = (ArrayList<UserInfo>) dbh.getUserInfo(null, null,null, null, null);
			if(mUserInfoList.size()!=0){
			setData();
			}
			dp.dismiss();
			super.onPostExecute(result);
		}
		
	}

}
